package com.lt.bookkeeping.Utils;

import android.os.Build;

import androidx.annotation.RequiresApi;

import java.util.concurrent.BlockingDeque;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * 线程池
 * @author LiuTong
 */
@RequiresApi(api = Build.VERSION_CODES.GINGERBREAD)
public class ThreadPoolUtils {
    private String TAG = getClass().getSimpleName()+"-";
    private ExecutorService executors;
    private final int coreSize = 3;
    private final int maxSize = 5;
    private final long keepTime = 3000;
    private final TimeUnit timeUnit = TimeUnit.SECONDS;
    private CustomThread threadFactory;
    private RejectedExecutionHandler rejectedExecutionHandler;
    private BlockingDeque<Runnable> blockingDeque = new LinkedBlockingDeque<>();

    private static ThreadPoolUtils instance;

    @RequiresApi(api = Build.VERSION_CODES.GINGERBREAD)
    public static ThreadPoolUtils getInstance() {
        if(instance == null){
            synchronized (ThreadPoolUtils.class){
                if(instance == null){
                    instance = new ThreadPoolUtils();
                }
            }
        }
        return instance;
    }

    class CustomThread implements ThreadFactory{

        private String typeName = "默认类型";
        public CustomThread(String typeName){
            this.typeName = typeName;
        }
        @Override
        public Thread newThread(Runnable r) {
            StringBuilder sb = new StringBuilder();
            sb.append(TAG).append(":正在执行:")
                    .append("\n线程类型:")
                    .append(typeName)
                    .append("\n线程名:")
                    .append(Thread.currentThread().getName());
            Thread t = new Thread(r,sb.toString());
            return t;
        }
    }

    @RequiresApi(api = Build.VERSION_CODES.GINGERBREAD)
    private ThreadPoolUtils(){


        rejectedExecutionHandler = new RejectedExecutionHandler() {
            @Override
            public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {

            }
        };

        executors = new ThreadPoolExecutor(
                coreSize,
                maxSize,
                keepTime,
                timeUnit,
                blockingDeque,
                new CustomThread("默认线程"),
                rejectedExecutionHandler);


    }

    public void runTask(Runnable... tasks){
        if(tasks!= null && tasks.length>0){
            for(Runnable r : tasks){
                executors.submit(r);
            }
        }
    }

}
